<?php
namespace common\services;

use common\models\News;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\db\mssql\PDO;

class NewsServices extends News
{

    /**
     * 展馆
     * @param $params
     * @return array
     */
    public function search($params){
        $model = News::find(false);
        $model->orderBy('id desc');

        $dataProvider = new ActiveDataProvider([
            'query' => $model,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['category_id']) && $params['category_id'] != '') {
            $model->andFilterWhere(['=', 'category_id', $params['category_id']]);
        }

        if (isset($params['status']) && $params['status'] != '') {
            $model->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or',
                ['like', 'title', $params['keywords']],
                ['like', 'desc', $params['keywords']],
                ['like', 'tag', $params['keywords']]
            ]);
        }

        //$sql = $model->createCommand()->getRawSql();

        return $dataProvider;
    }

    /**
     * 资讯列表
     * @param array $params
     * @return array
     */
    public function searchPage($params = array()){
        $model = News::find(false)
            ->andFilterWhere(['=', 'status', self::STATUS_FLAG_NORMAL]);

        if (isset($params['type'])){
            $model->andFilterWhere(['=', 'type', $params['type']]);
        }

        if (isset($params['categoryId'])){
            $model->andFilterWhere(['=', 'category_id', $params['categoryId']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or', ['like', 'title', $params['keywords']], ['like', 'content', $params['keywords']]]);
        }

        $count = $model->count(1);

        if ($count > 0){
            if (isset($params['ajax'])){
                $data = $model->select('id,title,litpic,desc,created_at')->asArray()->orderBy('order desc,id desc')->limit(5)->all();
                $page = null;
            }else {
                $page = new Pagination(['defaultPageSize' => $params['defaultPageSize'], 'totalCount' => $count]);
                $data = $model->orderBy('`order` desc,id desc')->offset($page->offset)->limit($page->limit)->asArray()->all();
            }
        }else{
            $page = $data = null;
        }
        return ['data' => $data, 'page' => $page];
    }

    /**
     * 相关文章
     * @param $tag
     * @param null $id
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getNewsRelated($tag, $id = null, $limit = 2){
        $model = News::find(false);
        $model->andFilterWhere(['=', 'status', News::STATUS_FLAG_NORMAL])
            ->addOrderBy("order desc, id desc");

        if (!empty($id)){
            $model->andFilterWhere(['<>', 'id', $id]);
        }

        if (!empty($tag)){
            $tags = explode(',', $tag);
            if (!empty($tags)) {
                $model->andFilterWhere(['like', 'tags', $tags]);
            }
        }

        $result = $model->asArray()->select("id,title,desc,litpic,created_at")->orderBy("`order` desc,id desc")->limit($limit)->all();

        return $result;
    }

    /**
     * 新闻列表
     * @param $params
     * @return array news 新闻数据  pagination 分页对象
     */
    public function newsList($params)
    {
        $model = News::find(false);
        $model->andFilterWhere(['status'=> self::STATUS_FLAG_NORMAL])->orderBy('order desc,id desc');

        if (isset($params['category_id']) && (int)$params['category_id'] > 0 ) {
            $model->andFilterWhere(['=', 'category_id', $params['category_id']]);
        }

        if (isset($params['status']) && $params['status'] != '') {
            $model->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['keywords'])){
            $model->andFilterWhere(['or',
                ['like', 'title', $params['keywords']],
                ['like', 'desc', $params['keywords']],
                ['like', 'tag', $params['keywords']]
            ]);
        }

        $total = $model->count();
        if ($total > 0) {
            $pagination = new Pagination(['totalCount' => $total, 'defaultPageSize' => $params['defaultPageSize']]);
            $news = $model->offset($pagination->offset)->limit($pagination->limit)->asArray()->all();
        }else{
            $pagination = null;
            $news = null;
        }
        return ['news'=> $news, 'pagination'=> $pagination];

    }

    /**新闻详情
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */

    public function detail($id)
    {
        $id = (int)$id;
        $news = News::findOne($id);
        if (empty($news)) {
            return false;
        }
        //增加访问次数统计
        News::addFieldNumber($id, 'views');

        $model = News::find(false)->andFilterWhere(['=', 'status', News::STATUS_FLAG_NORMAL])->asArray()->select('id,title')->orderBy("order desc, id desc")->all();
        $prev = $next = $tmp = [];
        if (!empty($model)) {
            $nextRow = false;
            foreach ($model as $key => $val) {
                if ($nextRow) {
                    $next = array(
                        'id' => $val['id'],
                        'title' => $val['title'],
                    );
                    //结束循环
                    break;
                }
                if ($val['id'] == $id) {
                    $nextRow = true;
                    if (!empty($tmp)) {
                        $prev = $tmp;
                    }
                }
                $tmp = array(
                    'id' => $val['id'],
                    'title' => $val['title'],
                );
            }
        }
        /*$cmd = \Yii::$app->db->createCommand("call news_detail_link(:id)")->bindValue(':id', $id, PDO::PARAM_INT);
        $res = $cmd->queryOne();
        $prev = $next = array();
        if (!empty($res['preID'])) {
            $prev = array(
                'id' => $res['preID'],
                'title' => $res['preTitle']
            );
        }
        if (!empty($res['nextID'])) {
            $next = array(
                'id' => $res['nextID'],
                'title' => $res['nextTitle']
            );
        }*/
        //相关文章
        $related = $this->getNewsRelated($news['tag'], $id, 3);
        return ['new'=>$news, 'prev'=> $prev, 'next'=> $next, 'related'=> $related];
    }
}
